import React, { createContext, useContext, useState, useCallback } from 'react';
import { Post } from '../types';
import { PostService } from '../services/PostService';
import { useAuth } from '../../auth/AuthContext';

interface PostContextType {
  posts: Post[];
  loading: boolean;
  error: string | null;
  createPost: (postContent: string, postTitle: string) => Promise<void>;
  updatePost: (postId: number, content: string) => Promise<Post>;
  deletePost: (postId: number) => Promise<void>;
  fetchPosts: () => Promise<void>;
  fetchUserPosts: (userId: number) => Promise<void>;
  updatePostComments: (postId: number, newComment: any) => void;
  user: any | null;
}

const PostContext = createContext<PostContextType | undefined>(undefined);

export const usePost = () => {
  const context = useContext(PostContext);
  if (!context) {
    throw new Error('usePost must be used within a PostProvider');
  }
  return context;
};

interface PostProviderProps {
  children: React.ReactNode;
}

export const PostProvider: React.FC<PostProviderProps> = ({ children }) => {
  const [posts, setPosts] = useState<Post[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const { user } = useAuth();

  const fetchPosts = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      const fetchedPosts = await PostService.getAllPosts();
      setPosts(fetchedPosts);
    } catch (err) {
      setError('获取帖子列表失败');
      console.error('获取帖子列表错误:', err);
    } finally {
      setLoading(false);
    }
  }, []);

  const fetchUserPosts = useCallback(async (userId: number) => {
    try {
      setLoading(true);
      setError(null);
      const userPosts = await PostService.getPostsByUserId(userId);
      setPosts(userPosts);
    } catch (err) {
      setError('获取用户帖子失败');
      console.error('获取用户帖子错误:', err);
    } finally {
      setLoading(false);
    }
  }, []);

  const createPost = useCallback(async (content: string, title: string) => {
    if (!user) {
      throw new Error('用户未登录');
    }

    try {
      setLoading(true);
      setError(null);
      const newPost = await PostService.createPost(content, title);
      setPosts(prev => [newPost, ...prev]);
    } catch (err) {
      setError('创建帖子失败');
      console.error('创建帖子错误:', err);
      throw err;
    } finally {
      setLoading(false);
    }
  }, [user]);

  const updatePost = useCallback(async (postId: number, content: string): Promise<Post> => {
    try {
      setLoading(true);
      setError(null);
      // 查找当前帖子以获取标题和其他信息
      const currentPost = posts.find(p => p.postId === postId);
      if (!currentPost) {
        throw new Error('找不到要更新的帖子');
      }
      
      // 调用 PostService.updatePost 方法
      await PostService.updatePost(
        postId,
        content,
        currentPost.postTitle // 保留原有标题
      );
      
      // 创建更新后的帖子对象，保留原有的用户信息和评论数
      const updatedPost: Post = {
        ...currentPost,
        postContent: content,
        // 保留原有的用户信息和评论数据
        user: currentPost.user,
        commentCount: currentPost.commentCount,
        comments: currentPost.comments
      };
      
      // 更新本地帖子列表
      setPosts(prev => prev.map(post =>
        post.postId === postId ? updatedPost : post
      ));
      
      return updatedPost;
    } catch (err) {
      setError('更新帖子失败');
      console.error('更新帖子错误:', err);
      throw err;
    } finally {
      setLoading(false);
    }
  }, [posts]);

  const deletePost = useCallback(async (postId: number) => {
    try {
      setLoading(true);
      setError(null);
      await PostService.deletePost(postId);
      setPosts(prev => prev.filter(post => post.postId !== postId));
    } catch (err) {
      setError('删除帖子失败');
      console.error('删除帖子错误:', err);
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  const updatePostComments = useCallback((postId: number, newComment: any) => {
    setPosts(prevPosts => prevPosts.map(post => {
      if (post.postId === postId) {
        return {
          ...post,
          comments: [...(post.comments || []), newComment]
        };
      }
      return post;
    }));
  }, []);

  return (
    <PostContext.Provider
      value={{
        posts,
        loading,
        error,
        createPost,
        updatePost,
        deletePost,
        fetchPosts,
        fetchUserPosts,
        updatePostComments,
        user
      }}
    >
      {children}
    </PostContext.Provider>
  );
};